<?php

namespace JsonLowCode\Form\Fields;

use JsonLowCode\Form\Traits\HasPrefix;
use JsonLowCode\UI\ImageVerify;
use JsonLowCode\UI\Input;
use JsonLowCode\Form\Abstract\FieldAbstract;
use JsonLowCode\Form\Rule;
use JsonLowCode\Form\Traits\HasClearable;
use JsonLowCode\Form\Traits\HasDisabled;
use JsonLowCode\Form\Traits\HasPlaceholder;
use JsonLowCode\Form\Traits\HasReadonly;
use JsonLowCode\Form\Traits\HasSize;
use JsonLowCode\Form\Traits\HasSuffix;

/**
 * @property Input $element
 */
class ImageVerifyField extends FieldAbstract
{
    use HasDisabled, HasSize, HasPlaceholder, HasClearable, HasReadonly, HasPrefix, HasSuffix;

    protected string $type = "text";

    protected ImageVerify $imageCode;

    protected string|null $placeholder = null;

    protected function booting(): void
    {
        $this->element = new Input($this->type);
        $this->element->styles(['--n-padding-right'=>0]);

        $this->imageCode = new ImageVerify();
        if (is_string($this->label)){
            $this->placeholder("请输入".$this->label);
        }else{
            $this->placeholder("请输入内容");
        }
        $this->setValue();
    }

    public function defaultValue(mixed $value = null): static
    {
        if (!is_array($value)){
            $value = strval($value);
        }
        return parent::defaultValue($value);
    }

    /**
     * @return $this
     */
    public function setValue(): static
    {
        $data = $this->form->getData();
        if ($data){
            $this->value = $data->value($this->field);
        }
        return $this;
    }

    /**
     * 设置rule验证规则
     * @param string $codeField
     * @param string $message
     * @return $this
     */
    public function validator(string $codeField = "", string $message = "验证码不正确"): static
    {
        $key = $codeField?$this->field."_code_".$codeField:$this->field."_code";
        $this->element->setState($key,"");
        $codeKey = "this.".$key;
        $this->imageCode->modelValue($codeKey);
        $this->rule(function (Rule $rule) use ($message, $codeKey) {
            $rule->message($message)->validator("function(rule, value){
                if (value.trim()!=null && value !== {$codeKey}) {
                    return Promise.reject(rule.message);
                }
                return Promise.resolve();
            }")->trigger(['input','blur']);
        });
        return $this;
    }

    protected function render(): void
    {
        if ($this->placeholder!=null){
            $this->element->placeholder($this->placeholder);
        }
        $this->element->slotSuffix($this->imageCode);
    }
}
